var GlobalConfig = require('../../../../config/config.json');
var roomManager = require('../../../logic/world/roomManager');
var LogicSubModules = require("../../../logic/sub");
var gameUtil = require("../../../util/gameUtil");
var systemConfig = require('../../../../config/systemConfig.json');
module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

var handler = Handler.prototype;

handler.create = function (msg, session, next) {
    var self = this;
    var uid = session.uid;

    if (roomManager.getUserRoomId(uid)) {
        next(null, {code: Code.ALREADY_IN_ROOM});
        return;
    }

    if (msg.scene || msg.matchId) {
        next(null, {code: Code.ARGS_INVALID});
        return;
    }

    var SubLogic = gameUtil.getSubLogic(msg.gameType);
    if (!SubLogic) {
        next(null, {code: Code.GAME_TYPE_INVALID});
        return;
    }

    var subConfig = SubLogic.Config.SubType[msg.subType];
    if (!subConfig) {
        next(null, {code: Code.SUB_TYPE_INVALID});
        return;
    }

    if (!SubLogic.Rule.checkCreateRoomArgs(msg)) {
        next(null, {code: Code.ARGS_INVALID});
        return;
    }

    var now = Date.getStamp();
    var activityCreateRoom = gGlobalManager.getConfig("activityCreateRoom");
    if (activityCreateRoom && now >= activityCreateRoom.startTime && now < activityCreateRoom.endTime) {
        msg.needResourceRate = activityCreateRoom.rate || 0;
    }

    var needResource = gameUtil.calcCreateRoomNeedResource(SubLogic, msg);
    var useResource = clone(needResource);
    // if(msg['costMode'] == Def.RoomCostMode.AA) {
    //     var playerNum = gameUtil.calcRoomMaxPlayer(subConfig, msg);
    //     needResource = ExObject.mulNew(needResource, 1/playerNum, Math.ceil);
    // }
    //代开房间扣钻检查
    //if (msg.agency) {

    var rooms = roomManager.queryCreatRooms(uid);
    if (rooms.length > 0) {
        var first = clone(rooms[0]["need"]);
        for (var i = 1; i < rooms.length; ++i) {
            var temp = clone(rooms[i]["need"]);
            first = ExObject.merge(first, temp);
        }
        needResource = ExObject.merge(first, needResource);
    }

    var player = null;
    var rid = 0;

    async.series([
        function (cb) {
            gPlayerManger.getPlayer(uid, function (thePlayer) {
                player = thePlayer;
                if (!thePlayer) {
                    cb(Code.DB_ERROR);
                    return;
                }

                if (!player.checkResource(needResource)) {
                    cb(Code.LACK_OF_RESOURCE);
                    return;
                }

                cb();
            });
        },
        function (cb) {
            //if (roomManager.getUserRoomId(uid)) {
            //    cb(Code.ALREADY_IN_ROOM); return;
            //}
            if (msg["agency"]) {
                var addOptions = {'agency': true};
                if (msg['index']) {
                    addOptions['index'] = msg['index'];
                }

                rid = roomManager.addCardRoom(msg.gameType, msg.subType, uid, useResource, addOptions);
            } else {
                rid = roomManager.addCardRoom(msg.gameType, msg.subType, uid, useResource);
            }
            if (!rid) {
                cb(Code.ROOM_ALLOC_FAILED);
                return;
            }

            cb();
        },
        function (cb) {
            msg.rid = rid;
            session.set('rid', rid);
            self.app.rpc.game.roomRemote.create(session, uid, msg, function (code) {
                if (code) {
                    roomManager.delRoom(rid);
                    cb(code);
                    return;
                }

                //开房信息存储
                var roomType = Def.RoomType.CARD;
                if (msg["agency"]) {
                    roomType = Def.RoomType.AGENCY;
                }

                DB.createrooms.save({
                    "_id": rid,
                    "creator": uid,
                    "type": roomType,
                    "gameType": msg.gameType,
                    "subType": msg.subType,
                    "time": Date.parse(new Date()),
                }, function (err) {
                    if (err)
                        console.log("save errr")
                });
                cb();
            });
        }
    ], function (code) {
        if (code) {
            next(null, {code: code});
            return;
        }
        if (msg["agency"]){
            next(null, {"rid": rid,"info":msg});
            return;
        }
        next(null, {"rid": rid});
    });
};

handler.enter = function (msg, session, next) {
    var self = this;

    var uid = session.uid;
    var player = null;

    if (isNaN(msg.rid)) {
        next(null, {code: Code.ARGS_INVALID});
        return;
    }

    var rid = +msg.rid;
    var oldRoomId = roomManager.getUserRoomId(uid);
    //if (oldRoomId && oldRoomId != rid) {
    //    next(null, {code: Code.ALREADY_IN_ROOM}); return;
    //}

    var theRoom = null;     // 房间

    async.series([
        function (cb) {
            gPlayerManger.getPlayer(uid, function (thePlayer) {
                if (!thePlayer) {
                    cb(Code.DB_ERROR);
                    return;
                }

                player = thePlayer;
                cb();
            });
        },
        function (cb) {
            var room = roomManager.getRoom(rid);
            if(!room) {
                cb(Code.ROOM_INVALID);
                return;
            }
            var groups = player.user.groups;
            var isMember = false;
            if (groups) {
                groups.forEach(function (id) {
                    if (id == room.creator) {
                        isMember = true;
                    }
                })
            }
            if(!systemConfig["UseType"]["Group"]){
                isMember = true;
            }

            theRoom = room;

            session.set('rid', rid);
            msg.sid = session.frontendId;
            msg.user = player.buildGameUser(msg.gameType, msg.subType, msg.scene);
            msg.isMember = isMember;

            if (Def.isMatchRoomId(rid)) {
                msg.user.matchInfo = gMatchManager.getUserMatchInfo(uid);
            }

            self.app.rpc.game.roomRemote.enter(session, uid, msg, function (code, resp) {
                if (code) {
                    cb(code);
                    return;
                }

                roomManager.userEnterRoom(uid, rid);
                session.push('rid');

                next(null, resp);
                cb();
            });
        },
        function(cb) {
            if (theRoom.agency) {   // 更新代开房间信息
                gPlayerManger.getPlayer(theRoom.creator, function (thePlayer) {
                    if (thePlayer) {

                        var msg = { rid: rid };
                        self.app.rpc.game.roomRemote.query(session, uid, msg, function (code, info) {
                            if (!code) {
                                thePlayer.send("onRoomsChange", info);
                            }
                        });

                    }
                });
            }

            cb();
        }
    ], function (code) {
        if (code) {
            next(null, {code: code, route: ""});
        }
    });
};

handler.enterScene = function (msg, session, next) {

    var self = this;
    var uid = session.uid;
    var player = null;
    var rid = 0;

    logger.debug("uid=%d enterScene msg=%j", uid, msg);

    var SubLogic = LogicSubModules[msg.gameType];
    if (!SubLogic) {
        next(null, {code: Code.GAME_TYPE_INVALID});
        return;
    }

    var subConfig = SubLogic.Config.SubType[msg.subType];
    if (!subConfig) {
        next(null, {code: Code.SUB_TYPE_INVALID});
        return;
    }

    var sceneConfig = subConfig.scenes ? subConfig.scenes[msg.scene] : null;
    if (!sceneConfig) {
        next(null, {code: Code.GANE_SCENE_INVALID});
        return;
    }

    async.series([
        function (cb) {
            gPlayerManger.getPlayer(uid, function (thePlayer) {
                player = thePlayer;
                if (!thePlayer) {
                    cb(Code.DB_ERROR);
                    return;
                }

                var code = gameUtil.checkSceneRoomCoin(sceneConfig, player.getResource('coin'));
                cb(code);
            });
        },
        function (cb) {
            if (roomManager.getUserRoomId(uid)) {
                cb(Code.ALREADY_IN_ROOM);
                return;
            }

            rid = roomManager.selectSceneRoom(msg.gameType, msg.subType, msg.scene);
            if (rid) {
                cb();
                return;
            }
            msg.options = sceneConfig.options;
            var roomPlayerNum = gameUtil.calcRoomMaxPlayer(subConfig, msg);
            rid = roomManager.addSceneRoom(msg.gameType, msg.subType, msg.scene, roomPlayerNum);
            if (!rid) {
                cb(Code.ROOM_ALLOC_FAILED);
                return;
            }

            session.set('rid', rid);
            msg.rid = rid;
            // msg.options = sceneConfig.options;
            self.app.rpc.game.roomRemote.create(session, uid, msg, function (code) {
                if (code) {
                    roomManager.delRoom(rid);
                    cb(code);
                    return;
                }

                cb();
            });
        },
        function (cb) {
            session.set('rid', rid);
            msg.rid = rid;
            msg.sid = session.frontendId;
            msg.user = player.buildGameUser(msg.gameType, msg.subType, msg.scene);
            self.app.rpc.game.roomRemote.enter(session, uid, msg, function (code, resp) {
                if (code) {
                    cb(code);
                    return;
                }

                roomManager.userEnterRoom(uid, rid);
                session.push('rid');

                next(null, resp);
                cb();
            });
        }
    ], function (code) {
        if (code) {
            next(null, {code: code, route: ""});
        }
    });
}